<?php
/**
 * 公用函数库
 *
 */
class Helper_Common {
    /**
     * 系统加密算法
     *
     * @param 加密原串 $var
     * @return string
     */
    public static function system_md5($var)
    {
        $_md5 = md5($var);
        $b = array();
        for ($i=0 ; $i<32 ; $i+=2)
        {
            if (fmod($i,3)){
                $b[] = strrev(substr($_md5,$i,2));
            }else{
                $b[] = substr($_md5,$i,2);
            }
        }
        return md5(implode('',$b));
    }
    static function cget($url)
    {
        $cu = curl_init();
        curl_setopt($cu, CURLOPT_URL, $url);
        curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($cu);
        curl_close($cu);
        return $ret;
    }

    static function get_data($url, $timeout = 5,$header=null) {
        $msg = $flat = '';
        if (strpos ( $url, 'http://' ) !== false || strpos ( $url, 'https://' ) !== false) {
            
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $url );
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
            if($header){
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            
            curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE ); // 跳过证书检查
            curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE ); // 不检查证书
            $res = curl_exec ( $ch );
            
            $flat = curl_errno ( $ch );
            if ($flat) {
                $msg = curl_error ( $ch );
            }
            curl_close ( $ch );
        } else {
            $context = stream_context_create ( array (
                    'http' => array (
                            'timeout' => 30 
                    ) 
            ) ); // 超时时间，单位为秒
            
            $res = file_get_contents ( $url, 0, $context );
        }
        return $res;
    }
    /*
     * 过滤发表内容
     */
    static function safeMsg($msg)
    {
        $msg = Helper_Common::substr_zh($msg, 40);
        $filename = Q::ini('app_config/ROOT_DIR').'/config/safekey.yaml';
        $badstring = file_get_contents($filename);
        return preg_replace("/$badstring/i",'',$msg);
    }
    /*
     *访问URL
     */
    static function curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if (is_array($postFields) && 0 < count($postFields))
        {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v)
            {
                if("@" != substr($v, 0, 1))//判断是不是文件上传
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&"; 
                }
                else//文件上传用multipart/form-data，否则用www-form-urlencoded
                {
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart)
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
            else
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
            }
        }
        $reponse = curl_exec($ch);
        
        if (curl_errno($ch))
        {
            throw new Exception(curl_error($ch),0);
        }
        else
        {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode)
            {
                throw new Exception($reponse,$httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }
/**
     * 
     *2011-12-30-下午05:30:52 by 460932465
     * 返回格式化后的字符串
     * @param 左边字符 $leftchar
     * @param 右边字符 $rightchar
     * @param 完整字符串 $string
     */
    static function get_split($leftchar,$rightchar,$string)
    {
        $a =  strpos($string,$leftchar) ;
        $b = strpos($string,$rightchar,$a);
        if($a === false && $b === false)
        {
            return false;
        }else
        {
            $c = substr($string,$a + strlen($leftchar),$b - $a - strlen($leftchar));
            $c = str_replace("\n","",$c);
            $c = str_replace("\r","",$c);
            $c = str_replace("\r\n","",$c);
            return $c;
        }
    }
    static function get_rnd($type,$len)
    {
        $key = array(
            0=>'0123456789'
        );
        $result = '';
        for ($i=1;$i<=$len;$i++)
        {
            $result .= rand(0, 9);  
        }
        return $result;
    }
    /*
     * 简单的日志功能
     */

    public static function log($str, $file='common') {
        if (!$file || !$str)
            return false;
        $file .= '_'.date('Y-m-d');
        $path = Q::ini('app_config/ROOT_DIR') . "/log/".date('Y-m-d');
        
        try {
            if(is_dir($path))
            {
                if(!is_writable($path))
                {
                    return false;
                }
            }else{
                @mkdir($path,0700);
            }
            $file = $path."/{$file}.log";
            if(!is_file($file))@touch($file);
                 @file_put_contents($file, date('Ymd H:i:s') . ' ' . $str . "\n", FILE_APPEND);
        } catch (Exception $e) {
        }
        
    }
    /*
     * 简单的日志功能
    */
    
    public static function Clilog($str, $file='common') {
        if (!$file || !$str)
            return false;
        $file .= '_'.date('Y-m-d');
        $path = Q::ini('app_config/ROOT_DIR') . "/log/".date('Y-m-d').'_cli';
        
        
        try {
            if(!is_dir($path))
            {
                @mkdir($path,0700);
                @chmod($path, 0666);
            }else{
                if(!is_writable($path))
                {
                    return false;
                }
            }
            $file = $path."/{$file}.log";
            if(!is_file($file))@touch($file);
                 @file_put_contents($file, date('Ymd H:i:s') . ' ' . $str . "\n", FILE_APPEND);
                
        } catch (Exception $e) {
        }
    }
    public static function get_ip()
    {
        if(isset($_SERVER['HTTP_X_REAL_IP']) && $_SERVER['HTTP_X_REAL_IP']<>'')
        {
            $onlineip = htmlentities($_SERVER['HTTP_X_REAL_IP']);
        }else if(isset($_SERVER['REMOTE_ADDR'])){
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }else{
            $onlineip = '127.0.0.1';
        }
        return $onlineip;
    }
    public static function trim($acctname)
    {
        $acctname = str_replace('+86', '', $acctname);
        $acctname = str_replace('+', '', $acctname);
        $acctname = str_replace('-', '', $acctname);
        $acctname = str_replace('.', '', $acctname);
        $acctname = str_replace(' ', '', $acctname);
        $acctname = str_replace('#', '', $acctname);
        $acctname = str_replace('*', '', $acctname);
         
        return trim($acctname);
    }
    /**
     *
     * 中文字符串截取
     * @param string $string
     * @param int $sublen
     * @param int $start
     * @param string $code
     */
    public static function substr_zh($string, $sublen, $start = 0, $code = 'UTF-8') {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all( $pa, $string, $t_string );
    
            if (count( $t_string[0] ) - $start > $sublen) return join( '', array_slice( $t_string[0], $start, $sublen ) ) . "...";
            return join( '', array_slice( $t_string[0], $start, $sublen ) );
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen( $string );
            $tmpstr = '';
    
            for($i = 0; $i < $strlen; $i ++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord( substr( $string, $i, 1 ) ) > 129) {
                        $tmpstr .= substr( $string, $i, 2 );
                    } else {
                        $tmpstr .= substr( $string, $i, 1 );
                    }
                }
                if (ord( substr( $string, $i, 1 ) ) > 129) $i ++;
            }
            if (strlen( $tmpstr ) < $strlen) $tmpstr .= "...";
            return $tmpstr;
        }
    }
    
    public static function replaceSafeAppname($str)
    {
        $str = str_replace('电信', '**', $str);
        $str = str_replace('联通', '**', $str);
        $str = str_replace('移动', '**', $str);
        $str = str_replace('铁通', '**', $str);
        return $str;
    }
    
public static function getPublicSet($key,$agentid)
    {
        $agentid = intval($agentid);
        $o = pubconfig::find('name = ? AND agent_id=?',trim($key),$agentid)->getOne();
        if($o->id())
        {
            return $o->value;
        }else{
            $o = pubconfig::find('name = ? AND agent_id=?',trim($key),1)->getOne();  
            if($o->id()){
                return $o->value;
            }else{
                return '';
            }   
        }
    }
    
    public static function setPublic($key,$val,$agentid)
    {
        $key = trim($key);
        $val = trim($val);
        $o = pubconfig::find('name = ? AND agent_id=?',trim($key),$agentid)->getOne();
        if(!$o->id())
        {
            $o = new pubconfig();
            $o->name = $key;
            $o->agent_id=$agentid;
        }
        $o->value = $val;
        $o->save();
    }
    /**
     * 限制请求频率
     * @param 唯一值 $uniqueKey
     * @param int|单次请求必须间隔的时间秒 $time
     */
    public static function limitFrequencyByRequest($uniqueKey,$time)
    {
        $cache_id = md5($uniqueKey);
        $isset = Q::cache($cache_id);
        if($isset === false)
        {
            Q::writeCache($cache_id, time());
            return true;
        }else{
            $isset = intval($isset);
            if(abs($isset-time())<$time)
            {
                return false;
            }else{
                Q::cleanCache($cache_id);
                return true;
            }
        }
    }
    /**
     * Generates an UUID
     *
     * @author     Anis uddin Ahmad
     * @param      string  an optional prefix
     * @return     string  the formatted uuid
     */
    static function  uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8) . '-';
        $uuid .= substr($chars,8,4) . '-';
        $uuid .= substr($chars,12,4) . '-';
        $uuid .= substr($chars,16,4) . '-';
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    /**
     * 返回请求的域名
     * @return string
     */
    static function getRequestHost()
    {
        $http = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!='off')?'https://':'http://';
        $http = $http.$_SERVER['SERVER_NAME'];
        $port = ($_SERVER["SERVER_PORT"]==80||$_SERVER["SERVER_PORT"]==443)?'':':'.$_SERVER["SERVER_PORT"];
        $url = $http.$port;
        $host = $url.'/';
        return $host;
    }
    /**
     * 返回请求的域名Domain
     * @return string
     */
    static function getRequestDomain()
    {
        $http = $_SERVER['SERVER_NAME'];
        return $http;
    }
    /**
     * 加载config下的YAML
     * @param string $filename
     * @return boolean|Ambigous <multitype:, number>
     */
    static function loadYAML($filename)
    {
        if(strpos($filename, '.'))
        {
            return false;
        }
        $yaml = Helper_YAML::loadCached(Q::ini('app_config/ROOT_DIR').'/config/'.$filename.'.yaml');
        return $yaml;
    }
    /**
     * 过滤文件目录 防止跨目录
     * @param string $filepath
     */
    static function safePath($filepath)
    {
        $filepath = str_replace('..', '.', $filepath);
        $filepath = str_replace('\\', '/', $filepath);
        return $filepath;
    }
    /**
     * 安全删除文件
     * @param unknown $file
     */
    static function safeDelFile($file)
    {
        $file = self::safePath($file);
        $realFile = realpath($file);
        $realFile = str_replace('\\', '/', $realFile);
        $safePath = Q::ini('app_config/ROOT_DIR').'/public/';
        $safePath = str_replace('\\', '/', $safePath);
        
        if(strpos($realFile, $safePath) === false)
        { 
            return false;//不在安全目录
            
        }else{
            if(is_file($realFile))
            {
                @unlink($realFile);
                Helper_Common::log($realFile,'DELFILE');
            }
        }
        
    }
    
    static function get_PowerList()
    {
        if(defined("NTS_SHOP_TAOBAO") && NTS_SHOP_TAOBAO == TRUE){
            return  array(
                    1=>array(
                            'title'=>'商家信息管理',
                            'submenu'=>array(
                                    '信息修改'=>array('agentmanage/edit','dialog'),
                                    '手机端顶部图片管理'=>array('banner/index','navTab'),
                                    '商家列表' => array('agentmanage/businessmanage','navTab'),
                                    '商家用户管理' => array('agentmanage/users','navTab'),
                                    '账单查询'=> array('agentmanage/bill','navTab'),
                                    '群发短信'=>array('agentmanage/sendmsg','navTab'),
                            )
                    ),
            
                    2=>array(
                            'title'=>'充值卡管理',
                            'submenu'=>array(
                                    '卡密管理' =>array ('mzcard/index','navTab'),
                                    '卡号充值' => array('mzcard/cardpay','navTab'),
                                    '空中充值' =>array ('mzcard/moneypay','navTab'),
                                    '充值记录' =>array ('mzcard/paylog','navTab'),
                                    '划卡记录' =>array ('mzcard/transfercardlog','navTab'),
                            )
                    ),
//                  3=>array(
//                             'title'=>'红包管理',
//                             'submenu'=>array(
//                                     '商家红包' => array('redpackets/index','navTab'),
                                
//                             )
//                     ),
                    4=>array(
                            'title'=>'商城管理',
                            'submenu'=>array(
                                    '商品管理' => array('product/index','navTab'),
                                    '订单管理'=>array( 'order/view','navTab'),
                            )
                    ),
                    5=>array(
                            'title'=>'优惠券管理',
                            'submenu'=>array(
                                    '优惠券设置' => array('coupon/index','navTab'),
                                    '优惠券领用记录' => array('coupon/getlog','navTab'),
                                    '优惠券额度兑换' => array('coupon/withdraw','navTab'),
                            )
                    ),
                     6=>array(
                            'title'=>'抽奖管理',
                            'submenu'=>array(
                                    '奖券管理' => array('movelottery/index','navTab'),
                                    '抽奖设置' => array('lottery/lotteryset','navTab'),
                                    '奖品管理' => array('lottery/index','navTab'),
                                    '抽奖记录' => array('lottery/lotterylog','navTab'),
                            )
                    ),
                   7=>array(
                            'title'=>'动态管理',
                            'submenu'=>array(
                                    '动态列表'=>array('move/index','navTab'),
                            )
                    ),
                    8=>array(
                            'title'=>'日志记录',
                            'submenu'=>array(
                                    '系统日志'=>array('logs/system','navTab'),
                            )
                    ),
            );
        }else{
            
            return  array(
                    1=>array(
                            'title'=>'商家信息管理',
                            'submenu'=>array(
                                    '信息修改'=>array('agentmanage/edit','dialog'),
                                    '手机端顶部图片管理'=>array('banner/index','navTab'),
                                    '商家列表' => array('agentmanage/businessmanage','navTab'),
                                    '商家用户管理' => array('agentmanage/users','navTab'),
                                    '账单查询'=> array('agentmanage/bill','navTab'),
                                    '群发短信'=>array('agentmanage/sendmsg','navTab'),
                            )
                    ),
            
                    2=>array(
                            'title'=>'充值卡管理',
                            'submenu'=>array(
                                    '卡密管理' =>array ('mzcard/index','navTab'),
                                    '卡号充值' => array('mzcard/cardpay','navTab'),
                                    '空中充值' =>array ('mzcard/moneypay','navTab'),
                                    '充值记录' =>array ('mzcard/paylog','navTab'),
                                    '划卡记录' =>array ('mzcard/transfercardlog','navTab'),
                            )
                    ),
//                  3=>array(
//                             'title'=>'红包管理',
//                             'submenu'=>array(
//                                     '商家红包' => array('redpackets/index','navTab'),
                                
//                             )
//                     ),
                    4=>array(
                            'title'=>'商城管理',
                            'submenu'=>array(
                                    '商品管理' => array('product/index','navTab'),
                            )
                    ),
                    5=>array(
                            'title'=>'优惠券管理',
                            'submenu'=>array(
                                    '奖券管理' => array('movelottery/index','navTab'),
                                    '优惠券设置' => array('coupon/index','navTab'),
                                    '优惠券领用记录' => array('coupon/getlog','navTab'),
                                    '优惠券额度兑换' => array('coupon/withdraw','navTab'),
                            )
                    ),
                          6=>array(
                            'title'=>'抽奖管理',
                            'submenu'=>array(
                                    '奖品管理' => array('lottery/index','navTab'),
                                    '抽奖记录' => array('lottery/lotterylog','navTab'),
                                    '抽奖设置' => array('lottery/lotteryset','navTab'),
                            )
                    ),
                     7=>array(
                            'title'=>'动态管理',
                            'submenu'=>array(
                                    '动态列表'=>array('move/index','navTab'),
                            )
                    ),
                    8=>array(
                            'title'=>'日志记录',
                            'submenu'=>array(
                                    '系统日志'=>array('logs/system','navTab'),
                            )
                    ),
            );
            
        }
  
    }
    /**
     * 判断是否本地访问
     * @return boolean
     */
    public static function isLocalhost()
    {
        $limit = NTS_LIMIT_IP.',127.0.0.1';
        $limit = explode(',', $limit);
        $ip = $_SERVER['REMOTE_ADDR'];
        return in_array($ip, $limit);
    }
    
    /**
     * 生成UUID
     * @return string
     */
     static function guid(){
        if (function_exists('com_create_guid')){
            $uuid= com_create_guid();
            $uuid=substr($uuid, 1,strlen($uuid)-2);
            return $uuid;
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = // "{"
            substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);// "}"           
            return $uuid;
        }
    }
    /*
     * 占位符自动转换
    */
    public static function placeholder_exchange($str,$tel=null,$appid=0){
    
    
        if(!empty($str)){
            //替换手机号码
    
            if(!empty($tel)){
                if(strpos($str , '{tel}') !== false){
                    $str  = str_replace('{tel}', $tel, $str );
                }
                 
            }
            //替换代理id
            if(!empty($appid)){
                if(strpos($str , '{appid}') !== false){
                    $str  = str_replace('{appid}', $appid, $str );
                     
                }
                //替换代理appkey
                $o = acctclientkey::find ( 'appid = ?', intval ( $_SESSION['user']['agent_id'] ) )->getOne ();
                if ($o->id ()) {
                    if(strpos($str , '{appkey}') !== false){
                        $str  = str_replace('{appkey}', $o->appkey, $str );
                    }
                }
            }
    
            return $str;
        }
    }
    static function getjw($city){

        $url = "http://api.map.baidu.com/geocoder?address=$city&output=json&key=37492c0ee6f924cb5e934fa08c6b1676";
        $url = urlencode($url);
        $res = Helper_Common::get_data($url);
        return $res;
    }

    /*
     * post请求
     */
    static function cpost($url,$str)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//禁止直接显示获取的内容 重要
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
        $ret = curl_exec($ch);
        return $ret;
    }
    static function wx_get_token($appid,$appkey) {
        $cache_id = 'webshare_accesstoken';
        $data = Q::cache ( $cache_id );
        if($data !== false && $data){
            return $data;
        }else{
          //AppSecret(应用密钥)
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appkey;
            $res = Helper_Common::get_data($url);
            $res = json_decode($res, true);
            //这里应该把access_token缓存起来，至于要怎么缓存就看各位了，有效期是7200s     
            Q::writeCache ( $cache_id, $res['access_token'],array('life_time'=>7000) );
            return $res['access_token'];
        }
    }
    //获取微信公从号ticket
    static function wx_get_jsapi_ticket($token) {
        $cache_ids = 'webshare_ticket';
        $datas = Q::cache ( $cache_ids );
        if($datas !== false && $datas){
            return $datas;
        }else{
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $token);
            $res = Helper_Common::curl($url);
            $res = json_decode($res, true);
            //这里应该把access_token缓存起来，至于要怎么缓存就看各位了，有效期是7200s   
            Q::writeCache ( $cache_ids, $res['ticket'],array('life_time'=>7000) );
            return $res['ticket'];
        }
    }

    // 以POST方式提交数据
    static function post_data($url, $param, $type = 'json', $return_array = true, $useCert = []) {
        $type === false && $type = 'json'; // 兼容老版本
        $type === true && $type = 'file'; // 兼容老版本
        if ($type == 'json' && is_array ( $param )) {
            $param = json_encode ( $param, JSON_UNESCAPED_UNICODE );
        } elseif ($type == 'xml' && is_array ( $param )) {
            $param = Helper_Common::ToXml ( $param );
        }
        // 初始化curl
        $ch = curl_init ();
        // 设置超时
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
        if(version_compare(phpversion(),'7.0') <0){
            if (class_exists ( '/CURLFile' )  ) { // php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
            //curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, true );
            } else {
                if (defined ( 'CURLOPT_SAFE_UPLOAD' )) {
                    curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false );
                }
            }
        }
        
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, true );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
        
        // 设置header
        if ($type == 'file') {
            $header [] = "content-type: multipart/form-data; charset=UTF-8";
            curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        } elseif ($type == 'xml') {
            curl_setopt ( $ch, CURLOPT_HEADER, false );
        } else {
            $header [] = "content-type: application/json; charset=UTF-8";
            curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        }
        
        // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {

            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        }
        // curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        //Helper_Common::curl_redir_exec($ch);
        curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param );
        // 要求结果为字符串且输出到屏幕上
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        // 使用证书：cert 与 key 分别属于两个.pem文件
        if (isset ( $useCert ['certPath'] ) && isset ( $useCert ['keyPath'] )) {
            curl_setopt ( $ch, CURLOPT_SSLCERTTYPE, 'PEM' );
            curl_setopt ( $ch, CURLOPT_SSLCERT, $useCert ['certPath'] );
            curl_setopt ( $ch, CURLOPT_SSLKEYTYPE, 'PEM' );
            curl_setopt ( $ch, CURLOPT_SSLKEY, $useCert ['keyPath'] );
        }
        
        $res = curl_exec ( $ch );
        $flat = curl_errno ( $ch );
        $msg = '';
        if ($flat) {
            $msg = curl_error ( $ch );
        }
            curl_close ( $ch );
        if ($flat) {
            return [ 
                    'curl_erron' => $flat,
                    'curl_error' => $msg 
            ];
        } else {
            if ($return_array && ! empty ( $res )) {
                $res = $type == 'xml' ? Helper_Common::FromXml ( $res ) : json_decode ( $res, true );
            }
            
            return $res;
        }
    }
    /**
     * 输出xml字符
     */
    static function ToXml($arr = []) {
        if (! is_array ( $arr ) || count ( $arr ) <= 0) {
            exit ( "数组数据异常！" );
        }
        
        $xml = "<xml>";
        foreach ( $arr as $key => $val ) {
            if (is_numeric ( $val )) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * 将xml转为array
     */
    static function FromXml($xml) {
        if (! $xml) {
            exit ( "xml数据异常！" );
        }
        // 将XML转为array
        $arr = json_decode ( json_encode ( simplexml_load_string ( $xml, 'SimpleXMLElement', LIBXML_NOCDATA ) ), true );
        return $arr;
    }
    //微信支付签名串排序
    static function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        
        $buff = trim($buff, "&");
        return $buff;
    }

    //数组格式化时间
    static function autoFormatTime($arr,$format="Y-m-d H:i:s"){
        for ($i=0; $i < count($arr); $i++) { 
            if(!empty($arr[$i]['addtime'])){
                $arr[$i]['addtime']=date($format,$arr[$i]['addtime']);
            }
            if(!empty($arr[$i]['created'])){
                $arr[$i]['created']=date($format,$arr[$i]['created']);
            }
        }
        return $arr;
    }

    /**
     * array_column() // 不支持低版本;
     * 以下方法兼容PHP低版本
     */
    static function _array_column(array $array, $column_key, $index_key=null){
        $result = [];
        foreach($array as $arr) {
            if(!is_array($arr)) continue;

            if(is_null($column_key)){
                $value = $arr;
            }else{
                $value = $arr[$column_key];
            }

            if(!is_null($index_key)){
                $key = $arr[$index_key];
                $result[$key] = $value;
            }else{
                $result[] = $value;
            }
        }
        return $result; 
    }
    static function curl_redir_exec($ch)
    {
        static $curl_loops = 0;
        static $curl_max_loops = 20;
        if ($curl_loops++ >= $curl_max_loops)
        {
            $curl_loops = 0;
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        list($header, $data) = explode("\n\n", $data, 2);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302)
        {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = @parse_url(trim(array_pop($matches)));
            if (!$url)
            {
                //couldn't process the url to redirect to
                $curl_loops = 0;
                return $data;
            }
            $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!$url['scheme'])
                $url['scheme'] = $last_url['scheme'];
            if (!$url['host'])
                $url['host'] = $last_url['host'];
            if (!$url['path'])
                $url['path'] = $last_url['path'];
            $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
            curl_setopt($ch, CURLOPT_URL, $new_url);
            debug('Redirecting to', $new_url);
            return curl_redir_exec($ch);
        } else {
            $curl_loops=0;
            return $data;
        }
    }


     /**
     * 消息推送http
     * @param $url
     * @param $post_data
     * @return bool|string
     */
    static function send_post( $url, $post_data ) {
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                //header 需要设置为 JSON
                'content' => $post_data,
                'timeout' => 60
                //超时时间
            )
        );
        $context = stream_context_create( $options );
        $result = file_get_contents( $url, false, $context );
        return $result;
    }

    /**
     * 获取随机字符串
     * @Author   xy
     * @DateTime 2020-01-13T14:04:26+0800
     * @param    integer                  $len     [description]
     * @param    boolean                  $special [description]
     * @return   [type]                            [description]
     */
    static function get_rand_str($len=10,$special=true){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
    
    //防注入
    static function clean($str)
    {
        $str=trim($str);
        $str=strip_tags($str);
        $str=stripslashes($str);
        $str=addslashes($str);
        $str=rawurldecode($str);
        $str=quotemeta($str);
        $str=htmlspecialchars($str);
        $pattern = 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile';
        preg_match('/'.$pattern.'/i', $str);
        return $str;
    }

    static function wxsafeMsg($appid,$key,$content,$type='msg'){
        $access_token = self::wx_get_token($appid,$key);
        if($type=='msg'){
            $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$access_token";
            $content = array('content'=>$content);
            $res = self::post_data($url,$content);
            return $res;
        }elseif($type=='pic'){
            $url = "'https://api.weixin.qq.com/wxa/img_sec_check?access_token=$access_token";
            $content = array('media'=>$content);
            $res = self::post_data($url,$content,'file');
            return $res;
        }
        
    }
    
    /**
     * 返回请求的域名
     * @return string
     */
    static function getJiqunHost()
    {
        $host=Q::ini('appini/jiqunurl');
        if(empty($host)){
            $host = Helper_Common::getRequestHost();
        }
        return $host;
    }

}

